﻿using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Web;
using System.Data;

using iSun.Common;

using iSun.Model;
using iSun.BLL.Base;
using iSun.BLL;


namespace iSun.Web.UI.Controls
{
    public class JsonData : BaseHandler
    {

        #region 自定义方法
        public virtual string GetListJson(IList<BaseEntity> list, int totalrecord)
        {
            string strFormat = "{\"total\":" + totalrecord.ToString() + ",\"items\":[";
            string str = list.ToJSON().Replace("\n", " ").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("@@", " ");
            strFormat = strFormat + str + "]}";
            return strFormat;
        }
        /// <summary>
        /// 获取有实体对象数据
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="iPageIndex"></param>
        /// <param name="iPageSize"></param>
        /// <param name="strOrder"></param>
        /// <param name="strCondition"></param>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetData(string strEntity, int iPageIndex, int iPageSize, string strOrder, string strCondition)
        {
            BaseEntity entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            _bll.entity = entity;
            BaseBussnies bll = _bll;// new BaseBussnies<BaseEntity>(entity);
            bll.PageIndex = iPageIndex;
            bll.PageSize = iPageSize == 0 ? 25 : iPageSize;
            bll.Order = strOrder;
            bll.Desc = "Yes";
            if (bll.PageIndex == 0)
            {
                return string.IsNullOrEmpty(strCondition) ? bll.GetEntitysByCondition("1=1") : bll.GetEntitysByCondition(strCondition);
            }
            else
            {
                return string.IsNullOrEmpty(strCondition) ? bll.GetEntitysSplitPage("1=1") : bll.GetEntitysSplitPage(strCondition);
            }
        }

        /// <summary>
        /// 获取没有实体对象的数据
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="iPageIndex"></param>
        /// <param name="iPageSize"></param>
        /// <param name="strOrder"></param>
        /// <param name="strCondition"></param>
        /// <returns></returns>
        public virtual DataTable GetNotEntityData(string strEntity, int iPageIndex, int iPageSize, string strOrder, string strCondition)
        {
            BaseEntity entity = new DataTableBaseEntity();
            var _entity = entity as DataTableBaseEntity;
            //_entity.TableKey = _entity.GetTableId();
            _entity.TableName = strEntity;
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            //System.Data.DataTable = bll.GetDataBySqlComm();
            bll.PageIndex = iPageIndex;
            bll.PageSize = iPageSize == 0 ? 25 : iPageSize;
            bll.Order = strOrder;
            bll.Desc = "Yes";
            System.Data.DataTable list;

            int totalrecord = bll.GetRowCount(strCondition);

            if (bll.PageIndex > 0)
            {
                list = string.IsNullOrEmpty(strCondition) ? bll.GetDataTableSplitPage("1=1") : bll.GetDataTableSplitPage(strCondition);
            }
            else
            {
                list = string.IsNullOrEmpty(strCondition) ? bll.GetDataTableByCondition("1=1") : bll.GetDataTableByCondition(strCondition);
            }
            return list;
        }

        /// <summary>
        /// 获取数据总数
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strCondition"></param>
        /// <returns></returns>
        public virtual int GetTotal(string strEntity, string strCondition)
        {
            BaseEntity entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            BaseBussnies bll = new BaseBussnies(entity);
            return bll.GetRowCount(strCondition);
        }


        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public virtual string getRoleCondition()
        {
            return this.User.GetDataCondition(this.FunctionID, GetStringFromQueryString("entity", ""));
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="condition">页</param>
        public virtual void SetCache(string entity, string condition, int total, int pagesize, string strOrder)
        {
            iSun.Common.WebCache.Insert(entity + "_" + this.UserName + "_Condition", condition, 60 * 20);

            int page = total / pagesize + 1;
            page = page > 20 ? 20 : page;
            for (int i = 1; i < page + 1; i++)
            {
                IList<BaseEntity> list = GetData(entity, i, pagesize, strOrder, condition);
                iSun.Common.WebCache.Insert(entity + "_" + this.UserName + "_" + i, GetListJson(list, total), 60 * 20);
            }
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="pageindex">页</param>
        /// <returns></returns>
        public virtual string GetDataCache(string entity, int pageindex)
        {
            return iSun.Common.WebCache.Get(entity + "_" + this.UserName + "_" + pageindex) as string;
        }

        public virtual string GetCondtionCache(string entity)
        {
            return iSun.Common.WebCache.Get(entity + "_" + this.UserName + "_Condition") as string;
        }

        public virtual void RefreshCache(string entity, string condition, int total, int pagesize, string strOrder)
        {
            int page = total / pagesize + 1;
            page = page > 20 ? 20 : page;
            #region 去掉缓存
            iSun.Common.WebCache.Remove(entity + "_" + this.UserName + "_Condition");
            for (int i = 1; i < page + 1; i++)
            {
                iSun.Common.WebCache.Remove(entity + "_" + this.UserName + "_" + i);
            }
            #endregion
            iSun.Common.WebCache.Insert(entity + "_" + this.UserName + "_Condition", condition, 60 * 20);

            for (int i = 1; i < page + 1; i++)
            {
                IList<BaseEntity> list = GetData(entity, i, pagesize, strOrder, condition);
                iSun.Common.WebCache.Insert(entity + "_" + this.UserName + "_" + i, GetListJson(list, total), 60 * 20);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public virtual void DojoDataRequest(HttpContext context)
        {
            string strEntity = this.GetStringFromQueryString("entity", "DatUser");            //对应的实体
            string strCondition = this.GetStringFromQueryString("condition", "");            //系统特定条件
            string strCustomCondition = this.GetStringFromQueryString("customCondition", "");//自定义条件
            int iPageIndex = this.GetIntFromQueryString("pageindex", 0);                     //第N页？
            int iPageSize = this.GetIntFromQueryString("pagesize", 0);                       //页记录数？
            string IsOnlyTotal = this.GetStringFromQueryString("onlyTotal", "false");         //是否只回传记录总数?
            string IsDesc = this.GetStringFromQueryString("desc", "false");                  //Yes or No

            // 系统数据权限
            strCondition = strCondition == "" ? getRoleCondition() : strCondition + (getRoleCondition() == "" ? "" : " and " + getRoleCondition());
            strCondition = strCondition == "" ? strCustomCondition : strCondition + (strCustomCondition == "" ? "" : " and " + strCustomCondition);


            string strType = this.GetStringFromQueryString("type", "");
            string strOrder = this.GetStringFromQueryString("order", "");
            strEntity = strEntity.Split(',')[0];

            BaseEntity entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            if (entity == null)
            {
                entity = new DataTableBaseEntity();
                var _entity = entity as DataTableBaseEntity;
                //_entity.TableKey = _entity.GetTableId();
                _entity.TableName = strEntity;

                BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
                //System.Data.DataTable = bll.GetDataBySqlComm();
                bll.PageIndex = iPageIndex;
                bll.PageSize = iPageSize == 0 ? 25 : iPageSize;
                bll.Order = strOrder;
                bll.Desc = "Yes";
                System.Data.DataTable list;

                int totalrecord = bll.GetRowCount(strCondition);
                if (IsOnlyTotal == "true")
                {
                    context.Response.Write("[{\"total\":" + totalrecord.ToString() + "}]");
                    return;
                }
                if (bll.PageIndex > 0)
                {
                    list = string.IsNullOrEmpty(strCondition) ? bll.GetDataTableSplitPage("1=1") : bll.GetDataTableSplitPage(strCondition);
                }
                else
                {
                    list = string.IsNullOrEmpty(strCondition) ? bll.GetDataTableByCondition("1=1") : bll.GetDataTableByCondition(strCondition);
                }
                if (list == null)
                {
                    context.Response.Write("[{\"N\":\"null\"}]");
                    return;
                }
      
                string strFormat = "{\"total\":" + totalrecord.ToString() + ",\"items\":";
                string str = iSun.Common.Globals.DataTableToJSON(list).Replace("\n", " ").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("@@", " ");
                strFormat = strFormat + (str == "" ? "0" : str) + "}";
               
                if (strType == "1")
                {
                    context.Response.Write("[" + str.Replace("null", "").Replace("[A]", "&") + "]");
                }
                else
                {
                    context.Response.Write(strFormat);
                }
            }
            else
            {
                string IsSetCache = this.GetStringFromQueryString("setcache", "false");
                string IsRefreshCache = this.GetStringFromQueryString("IsRefreshCache", "false");
                //记录数
                int totalrecord = GetTotal(strEntity, strCondition);

                if (IsOnlyTotal == "true")
                {
                    context.Response.Write("[{\"total\":" + totalrecord.ToString() + "}]");
                    return;
                }

                if (IsSetCache == "true")
                {
                    if (IsRefreshCache == "false")
                    {
                        SetCache(strEntity, strCondition, totalrecord, iPageSize, strOrder);
                    }
                    else
                    {
                        RefreshCache(strEntity, strCondition, totalrecord, iPageSize, strOrder);
                    }
                    return;
                }

                if ((GetCondtionCache(strEntity) == strCondition) && !string.IsNullOrEmpty(GetDataCache(strEntity, iPageIndex)))
                {
                    context.Response.Write(GetDataCache(strEntity, iPageIndex));
                    return;
                }

                IList<BaseEntity> list;
                list = GetData(strEntity, iPageIndex, iPageSize, strOrder, strCondition);

                if (list == null)
                {
                    context.Response.Write("{\"total\":" + totalrecord.ToString() + ",\"items\":[]}");
                    return;
                }

                if (strType == "1")
                {
                    string str = list.ToJSON().Replace("\n", " ").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("@@", " ");
                    context.Response.Write("[" + str.Replace("null", "").Replace("[A]", "&") + "]");
                }
                else
                {
                    context.Response.Write(GetListJson(list, totalrecord));
                }
            }

        }
        #endregion
    }
}
